package com.tianji.aigc.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeAudioTranscriptionOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import com.alibaba.cloud.ai.dashscope.audio.transcription.AudioTranscriptionModel;
import com.github.houbb.opencc4j.util.ZhConverterUtil;
import com.tianji.aigc.service.AudioService;
import com.tianji.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-04-26 18:19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AliBaiLianAudioServiceImpl implements AudioService {
    // 语音合成模型
    private final SpeechSynthesisModel speechSynthesisModel;
    // 语音识别模型
    private final AudioTranscriptionModel transcriptionModel;
    private static final String DEFAULT_MODEL_1 = "sensevoice-v1";


    /**
     * 文字转语音（TTS）
     *
     * @param text 待合成的文本内容
     * @return 异步响应输出
     */
    @Override
    public ResponseBodyEmitter ttsStream(String text) {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        Flux<SpeechSynthesisResponse> synthesisResponseFlux = speechSynthesisModel.stream(new SpeechSynthesisPrompt(text));
        // 订阅响应流并发送数据
        synthesisResponseFlux.subscribe(
                speechResponse -> {
                    try {
                        // 获取响应输出的数据，并发送到响应体中
                        ByteBuffer byteBuffer = speechResponse.getResult().getOutput().getAudio();
                        byte[] audioBytes = new byte[byteBuffer.remaining()];
                        byteBuffer.get(audioBytes);
                        emitter.send(audioBytes);
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },
                emitter::completeWithError,
                emitter::complete
        );
        return emitter;
    }

    @Override
    public String stt(MultipartFile multipartFile) {

        //将MultipartFile转换为Resource
        Resource audioResource = multipartFile.getResource();

        AudioTranscriptionPrompt audioTranscriptionPrompt = null;
            audioTranscriptionPrompt = new AudioTranscriptionPrompt(
                    // TODO 阿里百炼不支持本地音/视频文件直传
                    // new UrlResource(audioResource),
                    audioResource,
                    DashScopeAudioTranscriptionOptions.builder()
                            .withModel(DEFAULT_MODEL_1)
                            .build()
            );
        // 调用transcriptionModel进行语音识别
        AudioTranscriptionResponse response = transcriptionModel.call(audioTranscriptionPrompt);
        // 获取识别结果
        String output = response.getResult().getOutput();
        // 将繁体转换为简体
        return ZhConverterUtil.toSimple(output);
    }

    private String generateNewFileName(String originalFilename) {
        // 1.获取后缀
        String suffix = StringUtils.subAfter(originalFilename, ".", true);
        // 2.生成新文件名
        return UUID.randomUUID().toString(true) + "." + suffix;
    }
}
